<!-- 上传文件demo -->
<template>
  <div class=''>
    <el-upload class="avatar-uploader"
               action="http://admin.npwh.com:88/api/member/upload/uploadfile"
               :show-file-list="false"
               :on-success="handleAvatarSuccess"
               :before-upload="beforeAvatarUpload">
      <img v-if="fileList[0].url"
           :src="fileList[0].url"
           class="avatar">
      <i v-else
         class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: 'singleUpload2',
  props: {
    value: String,
    imgUrl: String
  },
  data () {
    // 这里存放数据
    return {
      // imageUrl: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {
    imageUrl () {
      return this.value
    },
    imageName () {
      if (this.value != null && this.value !== '') {
        let spl = this.value.split('/')
        return spl[spl.length - 2] + '/' + spl[spl.length - 1]
      } else {
        return null
      }
    },
    fileList () {
      return [{
        name: this.imageName,
        url: this.imageUrl
      }]
    },
    showFileList: {
      get: function () {
        return this.value !== null && this.value !== '' && this.value !== undefined
      },
      set: function (newValue) {
      }
    }
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    emitInput (val) {
      this.$emit('input', val)
    },
    handleAvatarSuccess (res, file) {
      // console.log(file)
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.fileList.pop()
      this.fileList.push({ name: file.name, url: res.data.imageUrl })
      this.emitInput(this.fileList[0].url)
    },
    beforeAvatarUpload (file) {
      // console.log(file.type)
      // const isJPG = file.type === 'image/jpeg'
      let allowSuffix = ['image/jpeg', 'image/png']
      let isAllow = allowSuffix.find(elem => elem === file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isAllow) {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // return isJPG && isLt2M
      return isAllow && isLt2M
    }
  }

}
</script>
<style scoped>
div >>> .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

div >>> .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>